
import NoDataImage from 'src/assets/no-data.png';
let Terms = {
  title: {
    confirm: {
      value: "确定",
      ReferenceExpr: "Schema.Controls.selectHelper.Terms.title.confirm",
    },
    cancel: {
      value: "取消",
      ReferenceExpr: "Schema.Controls.selectHelper.Terms.title.cancel",
    },
    pageSize: {
      value: "显示${pageStart}到${pageEnd}条，共 ${total}条",
      ReferenceExpr: "Schema.Controls.selectHelper.Terms.title.pageSize",
    },
    noData: {
      value: "没有符合条件的数据",
      ReferenceExpr: "Schema.Controls.fasr_select_tree_helpe.Terms.title.noData",
    },
    choise: {
      value: "请选择",
      ReferenceExpr: "Schema.Controls.selectHelper.Terms.title.choise",
    },
    sequence: {
      value: "序号",
      ReferenceExpr: "Schema.Controls.selectHelper.Terms.title.sequence",
    },
  },
  placeholder: {
    placeholder: {
      value: "请输入过滤条件",
      ReferenceExpr:
        "Schema.Controls.selectHelper.Terms.placeholder.placeholder",
    },
    enterQuery: {
      value: "回车查询",
      ReferenceExpr:
        "Schema.Controls.selectHelper.Terms.placeholder.enterQuery",
    },
  },
};
for (let i in Terms) {
  for (let j in Terms[i]) {
    //console.log(Terms[i][j].ReferenceExpr)
    let data = Terms[i][j].ReferenceExpr.split(".").reduce(
      (prev, cur) => {
        try {
          if (!!prev[cur]) {
            return prev[cur];
          } else {
            return Terms[i][j].value;
          }
        } catch (error) {
          return Terms[i][j].value;
        }
      },
      window._
        ? _.cloneDeep(window.localMessage ? localMessage["fas_common"] : {})
        : {}
    );
    Terms[i][j] = data;
  }
}
let OPTIONS_STATIC = {
  classificationType: "1", //分级类型 1:分级码 2:ParentID
  classification: "ID", //分级字段
  multiple: false, //是否多选
  isSingle: false, //是否单行
  helperCode: "hellow",
  historyEnable: true,
  historySaveCount: 3,
  iconEnable: false,
  readOnly: false,
  value: "",
  label: "",
  icon:
    "https://resource.teld.cn/teldimage/121/917a076e36fe44c49d626881a202db3f.png",
  labelField: "aaa",
  valueField: "bbb",
  dropDownWidth: "auto",
  readOnly: false,
  maxWidth: "600",
  indent: "2", //缩进
  childNodeName: "Children",
  placeholder: "",
  isLeaf: false, //叶子节点
  fieldMapping: [
    {
      field: "aaa",
      textAlign: "left",
      label: "编号",
      width: "",
    },
  ],
  tempFn: (e) => {
    console.log(e);
  },
};

function readCookie(n) {
  for (
    var t, r = n + "=", u = document.cookie.split(";"), i = 0;
    i < u.length;
    i++
  ) {
    for (t = u[i]; t.charAt(0) == " "; ) t = t.substring(1, t.length);
    if (t.indexOf(r) == 0) return t.substring(r.length, t.length);
  }
  return null;
}


function uuid() {
  function t() {
    return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
  }
  return t() + t() + "-" + t() + "-" + t() + "-" + t() + "-" + t() + t() + t();
}

function getElementPosition(el) {
  let elOptions = el.getBoundingClientRect();

  return {
    left: elOptions.left,
    top: elOptions.top,
    buttom: window.innerHeight - elOptions.height,
    height: elOptions.height,
    width: elOptions.width,
  };
}

!(function() {
  window["TeldTreeListHelperInstance"] = [];
  var TeldTreeListHelper = function(target, options) {
    this.eventList = {};
    this.options = options || {};
    this.element = target;
    //if (!this.options.helperCode) throw new Error("helperCode必填！");
    this.comID = uuid();
    this.LoadCss();
    this.Init();

    window.TeldTreeListHelperInstance[this.comID] = this;
  };

  //初始化
  TeldTreeListHelper.prototype.Init = function(notclear) {
    //初始化css
    this.LoadCss();
    //创建显示框
    this.CreatedInputElement();
    //初始化变量
    this.InitVar(notclear);
    this.TeldTreeListHelper_inputelement_input.setAttribute(
      "placeholder",
      this.checkList.length>0?'':this.placeholder
    );
  };
  //初始化变量
  TeldTreeListHelper.prototype.InitVar = function(notclear) {
    this.handleData = null;
    this.fIdChildMapList = [];
    this.oldHandleData = null;
    this.placeholder = this.options.placeholder || OPTIONS_STATIC.placeholder;
    this.TeldTreeListHelper_inputelement_input = this.element.querySelector(
      ".TeldTreeListHelper_inputelement_input"
    );
    this.getDropDownWidth = this.options.getDropDownWidth
    this.dropDownWidth =
      this.options.dropDownWidth || OPTIONS_STATIC.dropDownWidth;
    this.maxWidth = this.options.maxWidth || OPTIONS_STATIC.maxWidth;
    this.multiple = this.options.multiple || OPTIONS_STATIC.multiple;
    this.refTPopupProxy = this.options.refTPopupProxy;
    this.childNodeName =
      this.options.childNodeName || OPTIONS_STATIC.childNodeName;
    //缩进
    this.indent =
      this.options.indent.replace(/px/gi, "") || OPTIONS_STATIC.indent;
    //暂存选中数据
    if(!notclear){
      this.checkList = [];
    }
    this.loadNode = this.options.loadNode || OPTIONS_STATIC.tempFn;
    //叶子节点
    this.leaf = this.options.isLeaf;
    this.leafValue = this.options.leafValue;
    if (this.leafValue == "true"||this.leafValue ==1) {
      this.leafValue = true;
    } else if (this.leafValue == "false"||this.leafValue=='0') {
      this.leafValue = false;
    } else {
      this.leafValue = this.options.leafValue_custom;
    }
    this.refField = this.options.refField;
    //是否懒加载
    this.isLazy = this.options.isLazy || false;
    //映射关系
    this.fieldMapping =
      JSON.parse(JSON.stringify(this.options.fieldMapping)) || [];

    this.openIcon =
      (this.options.customIcons && this.options.openIcon) || 'icon-t-arrow-right'; //展开icon
    this.foldIcon =
      (this.options.customIcons && this.options.foldIcon) ||
      'icon-t-arrow-down'; //收起icon

    this.onlyCheckedNotLeaf = this.options.onlyCheckedNotLeaf;
    //屏蔽this.options.forcedAssociation
    this.options.forcedAssociation = false;
    if (this.options.forcedAssociation) {
      this.onlyCheckedNotLeaf = false;
    }
    //连接符
    this.linker = this.options.linker || ".";
    //显示排序
    this.showSequence = this.options.showSequence;
    //显示ico列
    this.showIconField =
      this.options.showIconField || this.options.fieldMapping[0]
        ? this.options.fieldMapping[0].field
        : "";
    if (this.showIconField == "2") {
      this.showIconField =
        this.options.iconField || this.options.fieldMapping[0]
          ? this.options.fieldMapping[0].field
          : "";
    }

    //显示排序 动态构造
    if (this.showSequence) {
      this.fieldMapping.unshift({
        field: "f_id",
        textAlign: "center",
        label: Terms.title.sequence,
        width: "100px",
      });
    } else {
      if (this.options.showIconField == "f_id") {
        this.showIconField = this.options.fieldMapping[0].field;
      }
    }

    if (this.multiple) {
      // this.fieldMapping.unshift({
      // 	field: "checkBoxTag",
      // 	textAlign: "left",
      // 	label: "",
      // 	width: "40px"
      // })
    }
    //回调函数
    this.confirm = this.options.confirm || OPTIONS_STATIC.tempFn;
    this.clearn = this.options.clearn || OPTIONS_STATIC.tempFn;

    //是否返回关联节点
    this.responseRelationNode = this.options.responseRelationNode;
    this.trStatus = {};
    this.fIdChildMapList = {};
    this.handleData = null;
    this.historyEnable = this.options.historyEnable;
    this.helperCode = this.options.helperCode;
    this.valueField = this.options.valueField;
    this.labelField = this.options.labelField;

    this.historySaveCount = this.options.historySaveCount;
    if (this.options.type == 1) {
      this.options.value_pid = this.options.classiFicationCode;
      this.options.lable_pid = this.options.classiFicationCode;
    }
    this.value_pid = this.options.value_pid;
    this.lable_pid = this.options.lable_pid;

    //this.placeholder = this.options.placeholder || '请输入查询条件'
    this.relationIcon = this.options.relationIcon;

    this.noData = this.options.noData || Terms.title.noData;
  };
  //加载在css
  TeldTreeListHelper.prototype.LoadCss = function() {
    let targetStyle = document.querySelector(".TeldTreeListHelper");
    let css = `
		// .TeldTreeListHelper_inputelement_input:disabled{
		// 	background-color:rgba(0,0,0,0.05)
		// }
		.TeldTreeListHelper_inputelement_input::-webkit-input-placeholder {
			color:rgba(0,0,0,.32)
		}


		.TeldTreeListHelper_inputelement {
			display: flex;
			align-items: center;
			justify-content: space-between;
			${this.options.isMobile ? "" : "border: 1px solid #CCCCCC;"}
			min-height: 32px;
			overflow: hidden;
			border-radius:2px;
			cursor: pointer;
			background:#fff;
		}
		${
      this.options.isMobile
        ? ""
        : `
		.TeldTreeListHelper_inputelement:hover{
			${
        this.options.readOnly
          ? ""
          : "border: solid 1px var(--t-color-hover) !important;box-shadow: 0px 0px 3px rgb(0 111 196 / 30%);"
      }

		}
		.TeldTreeListHelper_inputelement .tags span:hover{
			background:var(--t-color-background);
			color:var(--t-color);
			border: 1px solid var(--t-color-background);
	}`
    }
		.TeldTreeListHelper_inputelement .tags{
			padding:2px 0;
			margin:0;
			display:flex;
			${ this.options.readOnly?"":''};
    max-width: calc(100% - 30px);
		}
		.TeldTreeListHelper_inputelement .tags span{
			    height: 22px;
				margin: 1px 0;
			    padding: 0 5px;
			    display: flex;
			    line-height: 22px;
				margin-left:4px;
				border-radius:2px;
				font-size:12px;
				background: #F0F2F5 ;
				color: rgba(0,0,0, var(--t-color-opacity, /*批量处理90%透明度*/.9)) ;
				border: 1px solid #F0F2F5 ;
				align-items: center;

		}

		.TeldTreeListHelper_inputelement .tags span i{
			margin-left:6px;
		}
		.TeldTreeListHelper_inputelement .tags span:hover .close_tags{
			color:var(--t-color);
			background-color: var(--t-color);
		}
		.TeldTreeListHelper_inputelement .tags span:hover .close_tags::after{
			color:var(--t-color);
			background-color: var(--t-color);
		}

		.close_tags{
		    display: inline-block;
		    width: 8px;
		    height: 1px;
			background:rgba(0,0,0,.9);
		    transform: rotate(45deg);
			position: relative;

		}
		.close_tags::after{
		    content: '';
		    display: block;
		    width: 8px;
		    height: 1px;
		    background:rgba(0,0,0,.9);
		    transform: rotate(-90deg);
		}
		.close_tags:hover{
			background:var(--t-color-background);
		}
		.close_tags:hover::after{
			background:var(--t-color-background);
		}
		.TeldTreeListHelper_inputelement_input {
			display: inline-block;
			width: calc(100% - 10px);
			border: 0px;
			outline: 0;
			height: 30px;
			text-indent: 6px;
		}
		.TeldTreeListHelper_inputelementr_drop_icon {
			// width: 30px;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right:10px;
			height:30px;
		}
		.TeldTreeListHelper_inputelementr_drop_icon i{
			font-style:normal;
			transform: scale(0.5);

		}

		.teldTreeListContent_outSide{
			position: relative;
			max-height: 600px;
			width: 100%;
			height: auto;
			z-index: 9999;

			transform: translate(0px, 0px);
			transition: all 0s ease 0s;
			visibility: visible;
			opacity: 1;
			background:#fff;
			width:600px;
			border: 1px solid #ddd;
			background: #fff;
			box-shadow: 0 6px 12px rgb(0 0 0 / 18%);
      overflow: hidden;
		}
		.icon-angle-left {
		   margin: 0;
		   margin-top: 6px;
		   display: inline-block;
		   width: 0px;
		   height: 0px;
		   border: 5px solid;
		   border-right-color: transparent;
		   border-top-color: transparent;
		   border-bottom-color: transparent;
		}

		.icon-angle-down {
		    margin: 0 ;
		    margin-top: 6px;
		    display: inline-block;
		    width: 0px;
		    height: 0px;
		    border: 5px solid;
		    border-left-color: transparent;
		    border-right-color: transparent;
		    border-bottom-color: transparent;
        position:relative;
        top:2px;
		}

		.Teld_Tree_Hepler_Table {
		    border-spacing: 0px;
		    border-collapse: collapse;
			width: calc(100% - 24px);
		    border: rgb(221, 221, 221);
			table-layout: fixed;
			overflow:auto;
		}
		.Teld_Tree_Hepler_Table{
			background:#fff;

		}
		.Teld_Tree_Hepler_Table.header{
			    font-size: 14px;
			    border-collapse: collapse;
			    background-color: rgba(250,250,250,1);
			    color: rgba(0,0,0,0.56);

				margin:0 10px;
				height:38px;
				display: table;
		}
		.Teld_Tree_Hepler_Table.header tr th{
			background:#fff;
			border-bottom: 1px solid #ddd;
		}
    .Teld_Tree_Hepler_Table.header tr th:hover{
      border-left:0 !important;
      border-right:0 !important
    }
		.Teld_Tree_Hepler_Table_footer{
			padding:10px;
			display:flex;
			justify-content: end;
      background:#fff;
		}
		.Teld_Tree_Hepler_Table_footer span{
			    margin-left: 8px;
			    border: 1px solid rgb(220, 220, 220);
			    text-decoration: none;
			    display: inline-block;
			    border-radius: 2px;
			    width: 74px;
			    height: 32px;
			    font-size: 14px;
			    text-align: center;
			    line-height: 32px;
			    justify-content: center;
			    align-items: center;
			    display: flex;
			}
			.Teld_Tree_Hepler_Table_footer .Teld_Tree_Hepler_Table_footer_close:hover{

				color:var(--t-color);
				border:1px solid var(--t-color);
				cursor: pointer;
			}
			.Teld_Tree_Hepler_Table_footer .Teld_Tree_Hepler_Table_footer_save{
				color: rgba(255,255,255, var(--t-color-opacity, /*批量处理90%透明度*/0.90));
				background-color: var(--t-color);
				border: solid 1px var(--t-color);
			}
			.Teld_Tree_Hepler_Table_footer .Teld_Tree_Hepler_Table_footer_save:hover{
				cursor: pointer;
				color: rgba(255,255,255,0.70);
				background-color: var(--t-color-hover);
				border: solid 1px  var(--t-color-hover);
			}


		.Teld_Tree_Hepler_Table tr td  {
			border-left: 0;
			border-collapse: collapse;
			// border-bottom: 1px solid rgba(241,241,241,1);
			padding: 4px 8px;
			height: 30px;
			line-height: 30px;
			text-overflow: ellipsis;
			-moz-text-overflow: ellipsis;
			-o-text-overflow: ellipsis;
			-webkit-text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
			}
		}
		.Teld_Tree_Hepler_Table tr:hover{
			background:var(--t-color-background)
		}
		table tbody tr.level_odd{
		    background-color: #FFF;
		}
		table tbody tr.level_checked{
		    background-color: var(--t-color-background);
		}
		.c_pointer{
		    cursor: pointer;
		}
		.helpr_tree_loading {
			margin-right:10px;
			display:inline-block;
			color:rbga(0, 0, 0, .4) !important;
			font-size: 7px;
			overflow: hidden;
			width: 7px;
			height: 7px;
			border-radius: 50%;
			transform: translateZ(0);
			/* animation：规定完成动画所花费的时间，该属性必须规定，否则动画时长为0，无法播放 */
			animation: helpr_tree_loading_box 1.7s infinite ease, helpr_tree_loading_round 1.7s infinite ease;
		}
		@keyframes helpr_tree_loading_box {
			0% {
				box-shadow: 0 -0.83em 0 -0.4em, 0 -0.83em 0 -0.42em, 0 -0.83em 0 -0.44em, 0 -0.83em 0 -0.46em, 0 -0.83em 0 -0.477em;
			}
			5%,
			95% {
				box-shadow: 0 -0.83em 0 -0.4em, 0 -0.83em 0 -0.42em, 0 -0.83em 0 -0.44em, 0 -0.83em 0 -0.46em, 0 -0.83em 0 -0.477em;
			}

			10%,
			59% {
				box-shadow: 0 -0.83em 0 -0.4em, -0.087em -0.825em 0 -0.42em, -0.173em -0.812em 0 -0.44em, -0.256em -0.789em 0 -0.46em, -0.297em -0.775em 0 -0.477em;
			}
			20% {
				box-shadow: 0 -0.83em 0 -0.4em, -0.338em -0.758em 0 -0.42em, -0.555em -0.617em 0 -0.44em, -0.671em -0.488em 0 -0.46em, -0.749em -0.34em 0 -0.477em;
			}

			38% {
				box-shadow: 0 -0.83em 0 -0.4em, -0.377em -0.74em 0 -0.42em, -0.645em -0.522em 0 -0.44em, -0.775em -0.297em 0 -0.46em, -0.82em -0.09em 0 -0.477em;
			}
			100% {
				box-shadow: 0 -0.83em 0 -0.4em, 0 -0.83em 0 -0.42em, 0 -0.83em 0 -0.44em, 0 -0.83em 0 -0.46em, 0 -0.83em 0 -0.477em;
			}
		}

		@keyframes helpr_tree_loading_round {
			0% {
				transform: rotate(0deg);
				/* 开始旋转 div 元素 */
			}
			100% {
				transform: rotate(360deg);
				/* 结束旋转 div 元素 */
			}
		}
		.teldTree_search_inner{
			padding:10px;
			margin-top:10px;
			padding-bottom:0;
			position:relative;
      height:0;
      width:0;
      overflow:hidden;
      margin:0;
      padding:0;
		}
		.teldTree_search_inner input{
			    top: 8px;
			    font-size: 12px;
			    height: 30px;
			    border: 1px solid #ddd;
			    border-radius: 4px;
			    width: 100%;
			    outline: 0;
			    text-indent: 4px;
		}
		.teldTree_history{
			padding:0 12px;
			user-select: none;
			margin-top:12px;
		}
		.teldTree_history span .tree_helper_history_tags{
			display:inline-block;
			max-width:150px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-style:normal;
			user-select: none;
		}

		.teldTree_history span .tree_helper_history_icon{
			position: relative;
			user-select: none;
			position: relative;
			user-select: none;
			height: 12px;
			margin: 0;
			padding: 0;
			line-height: 12px;
			width: 12px;
			background: rgba(0,0,0,0);
      top:-10px;
      opacity:.6;
		}
		.teldTree_search_inner .tree_helper_history_icon{
			position: relative;
			top: -11px;
			user-select: none;
			position: absolute;
			user-select: none;
			right: 15px;
			top: 24px;
			cursor: pointer;
			background:rgba(0,0,0,.5) !important;
		}
		.teldTree_search_inner .close_tags::after{
			content: '';
			display: block;
			width: 8px;
			height: 1px;
			background:rgba(0,0,0,.5) !important;
			transform: rotate(-90deg);
		}



		.teldTree_history span{
			display:inline-block;
			border-radius: 20px;
			border-width: 1px;
			border-style: solid;
			text-align: center;
			text-indent: inherit;
			//border-color: var(--t-color-hover);
			height: 20px;
			//background-color: var(--t-color-background);
			margin: auto 1px;
			margin-bottom: -4px;
			padding: 0 8px;
			margin-right: 6px ;
			//color: var(--t-color);
			border: 0 !important;
			//background:var(--t-color-background);
			background: #F0F2F5 ;
			//color:var(--t-color);
			color: rgba(0,0,0, var(--t-color-opacity, /*批量处理90%透明度*/.9)) !important;
			border: 1px solid #F0F2F5 ;
			font-size:12px;
			line-height:20px;
			user-select: none;
			}

			.teldTree_history span:hover{
				background-color: var(--t-color-background) !important;
				cursor: pointer;
			}
			.teldTree_history span:hover i{
				color:var(--t-color)
			}
			.teldTree_history span:hover .close_tags{
				color:var(--t-color);
				background-color: var(--t-color);
			}
			.teldTree_history span:hover .close_tags::after{
				color:var(--t-color);
				background-color: var(--t-color);
			}
			#search_select_tree{
				position: absolute;
				background: #fff;
				z-index: 10000;
				/* width: 100%; */
				box-shadow: 2px 4px 8px #ccc;
				right: 10px;
				left: 10px;
				padding: 10px 0px;
				display:none;
				    max-height: 300px;
				    overflow: auto;
			}
			#search_select_tree p{
				margin:0;
				padding:5px 10px;
				cursor: pointer;
			}
			#search_select_tree span{
				font-size: 14px;
				color: rgba(0,0,0,0.56);
			}
			#search_select_tree p:hover{
				background:var(--t-color-background)
			}
			#search_select_tree p:hover span{
				color:var(--t-color-hover)
			}
			.Teld_Table_Hepler_Table{
				border-spacing: 0px;
				border-collapse: collapse;
				width: 100%;
				border: rgb(221, 221, 221);
				table-layout: fixed;
			}
			.Teld_Table_Hepler_Table tr td  {
				border-left: 0;
				border-collapse: collapse;
				border-bottom: 1px solid rgba(241,241,241,1);
				padding: 4px 8px;
				height: 30px;
				line-height: 30px;
				text-indent:10px;
			}
			.Teld_Table_Hepler_Table tr:hover{
				background:var(--t-color-background)
			}
			.custom-checkbox {
			  position: absolute;
			  z-index: -1;
			  opacity: 0;
			  padding-left:10px
			}
			.custom-checkbox + label {
			  cursor: pointer;
			  display: inline-flex;
			  align-items: center;
			  -webkit-user-select: none;
			  -moz-user-select: none;
			  -ms-user-select: none;
			  user-select: none;
			  margin-left:10px;
			  position: relative;
			  top: 2px;
			}
			.custom-checkbox + label::before {
			  content: '';
			  display: inline-block;
			  width: 1em;
			  height: 1em;
			  flex-shrink: 0;
			  flex-grow: 0;
			  border: 1px solid #c3c3c3;
			  border-radius: 0.25em;
			  margin-right: 0.5em;
			  background-repeat: no-repeat;
			  background-position: center center;
			  background-size: 50% 50%;
			}
			.custom-checkbox:disabled + label::before {
				background:#f1f1f1;
			  }
			.custom-checkbox:checked + label::before {
			  border-color: var(--t-color);
			  background-color: var(--t-color);
			  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
			}
			.custom-checkbox:not(:disabled):not(:checked) + label:hover::before {
			  border-color: var(--t-color);
			}
			.custom-checkbox:not(:disabled):active + label::before {
			  background-color:var(--t-color);
			}
			.custom-checkbox:focus:not(:checked) + label::before {
			  border-color: #c3c3c3;
			}
		`;
    if (!targetStyle) {
      //动态创建style 脚本
      var style = document.createElement("style");
      style.type = "text/css";
      style.setAttribute("class", "TeldTreeListHelper");
      style.innerHTML = css;
      document
        .getElementsByTagName("HEAD")
        .item(0)
        .appendChild(style);
    } else {
      targetStyle.innerHTML = css;
    }
  };
  //订阅通知
  TeldTreeListHelper.prototype.RegistorNotify = function(eventName, event) {
    this.eventList[eventName] = event;
  };
  //创建最外层输入框
  TeldTreeListHelper.prototype.CreatedInputElement = function() {
    let html = `
		<div class="TeldTreeListHelper_inputelement"${
      this.options.readOnly ? 'style="background-color:rgba(0,0,0,0.05)"' : ""
    } >
			<p class='tags'>

			</p>
			<input class="TeldTreeListHelper_inputelement_input" ${
        this.options.readOnly ? 'disabled="disabled"' : ""
      }/>
			<span class='TeldTreeListHelper_inputelementr_drop_icon' ${
        this.options.readOnly ? 'style="    opacity: 0;"' : ""
      }>
				<i class="icon"></i>
			</span>

		</div>
		`;
    this.element.innerHTML = html;
    this.dropIcon = this.element.querySelector(
      ".TeldTreeListHelper_inputelementr_drop_icon"
    );
    this.elemnt_input_outside = this.element.querySelector(
      ".TeldTreeListHelper_inputelement_input"
    );
    if (!this.eventList.openDrop) {
      this.RegistorNotify("openDrop", this.CreatedInputElementOutSide);
    }
    this.elemnt_input_outside.onfocus = (e) => {
      this.eventList.openDrop.call(this);
    };
    //回车下拉
    this.elemnt_input_outside.onkeyup = (e) => {
      let code = e.keyCode;
      if (code == 13) {
        this.eventList.openDrop.call(this);
      }
    };
    //点击按钮
    this.dropIcon.onclick = this.eventList.openDrop.bind(this);
  };
  //创建下拉节点
  TeldTreeListHelper.prototype.CreatedInputElementOutSide = function() {
    if (this.options.readOnly) return;


    if (window.TeldTreeListHelpers == this.comID) return;
    this.isBinded = false;
    //先清空
    for (let i in window.TeldTreeListHelperInstance) {
      window.TeldTreeListHelperInstance[i].CloseDrop();
    }
    window.TeldTreeListHelpers = this.comID;
    let treeListContent = this.options.dropDownElement
    // document.querySelector(
    //   ".teldTreeListContent_outSide"
    // );
    if (!treeListContent) {
      treeListContent = document.createElement("DIV");
      treeListContent.setAttribute(
        "class",
        "teldTreeListContent_outSide tree_" + this.comID
      );
      document.body.appendChild(treeListContent);
    } else {
      treeListContent.setAttribute(
        "class",
        "teldTreeListContent_outSide tree_" + this.comID
      );
    }
    //下拉之后的实例
    this.dropEle = treeListContent;
    let innerHtml = ``;
    this.fieldMapping.forEach((item) => {
      // 生成style
      let style = ``;
      if (item.textAlign) {
        style += `text-align:${item.textAlign};`;
      }
      if (item.width) {
        item.width = item.width.replace(/px/gi, "") + "px";
        style += `width:${item.width};`;
      } else {
        style += `width:auto;`;
      }
      innerHtml += `<th data-noresize style=${style}>${item.label}</th>`;
    });
    let searchInput = `
		<div class="teldTree_search_inner">
			<input placeholder='${Terms.placeholder.placeholder}' style='text-indent:10px' tabindex="${this.options.tabindex?this.options.tabindex:0}" />
			<i class='close_tags tree_helper_history_icon' style='display:none'></i>
			<div id="search_select_tree" style='display:none'></div>
		</div>
		`;
    let teldTree_history = `
		<div class="teldTree_history">

		</div>
		`;
    treeListContent.innerHTML = `
		${searchInput}
		${teldTree_history}
		<div style="max-height:400px;overflow:auto;user-select:none;height:400px;display: block;flex: 1 1 auto;" class='Teld_Table_Content'>
			<table  class="Teld_Tree_Hepler_Table header">
				<thead>
					<tr style="text-indent:10px;height:38px;position:relative;z-index:1000">
					${innerHtml}
					</tr>
				</thead>
				<div  >
					<tbody class='Teld_Tree_Hepler_Table' id="Tree_Tr_Content" ></tbody>
				</div>
				<div >
					<tbody  class="Teld_Table_Hepler_Table" id="Table_Tr_Content" ></tbody>
				</div>

			</table>


		</div>
		<p class="noData" style='text-align: center;padding: 20px 0 0 0;color: rgba(0,0,0,.9);display:none;height:400px;align-items: center;justify-content: center;flex-wrap: wrap;    flex-direction: column;}'>
      <img
                      style='display:inline-block;width:120px;height:120px'
                      src='${NoDataImage}'
                    />
<span style="display:inline-block;width:100%">
    ${this.noData}
    </span>
    </p>
		<div class="Teld_Tree_Hepler_Table_footer">
			<span class="Teld_Tree_Hepler_Table_footer_close">
				${Terms.title.cancel}
			</span>
			<span class="Teld_Tree_Hepler_Table_footer_save">
			${Terms.title.confirm}
			</span>
		</div>
		`;
    this.InitTree();
    //下拉内容变量
    this.treeListContent = treeListContent;
    setTimeout(() => {
      this.treeListContent.addEventListener('keyup',(e)=>{
        if(e.keyCode==9){
          this.CloseDrop()
        }
      })
    }, 500);

    this.RenderHIstory();
    this.renderPosition();
    this.BindEvent();
    setTimeout(() => {
      // treeListContent
      //   .querySelector(".teldTree_search_inner")
      //   .querySelector("input")
      //   .focus();
      treeListContent
        .querySelector(".teldTree_search_inner")
        .querySelector(".tree_helper_history_icon").onclick = (e) => {
        this.teldTree_search_inner.value = "";
        if (this.isSearching) {
          this.InitTree();
        }
        this.RenderSelect([]);
        this.treeListContent.querySelector("#Tree_Tr_Content").style.display =
          "";
        this.treeListContent.querySelector(
          ".Teld_Table_Hepler_Table"
        ).style.display = "none";
        e.target.style.display = "none";
      };

      //查询使用
      this.teldTree_search_inner.onkeydown = async (e) => {
        if(e.keyCode==9){
          return this.CloseDrop()
        }
        if (!this.isLazy) {
          return this.LazySearch.bind(this)();
        }

        if (window.delaySearch_treeHelper) {
          window.clearTimeout(window.delaySearch_treeHelper);
          window.delaySearch_treeHelper = null;
        }
        // if (e.keyCode == 13) {
        //   this.treeListContent.querySelector("#Table_Tr_Content").innerHTML =
        //     "";
        //   let res = this.options.loadNode({
        //     filter: this.teldTree_search_inner.value,
        //   });
        //   if (res instanceof Promise) {
        //     res = await res;
        //   }
        //   if (!res) {
        //     res = [];
        //   }
        //   this.RenderSelect([]);

        //   this.treeListContent.querySelector("#Tree_Tr_Content").style.display =
        //     "none";
        //   this.treeListContent.querySelector(
        //     ".Teld_Table_Hepler_Table"
        //   ).style.display = "";
        //   this.tableData = res;
        //   // this.RenderTable()
        //   res.forEach((item, index) => {
        //     item.f_id = index + 1 + "";
        //     this.treeListContent
        //       .querySelector("#Table_Tr_Content")
        //       .appendChild(this.CreateTable(item));
        //   });
        //   if (document.querySelector(".teldTreeListContent_outSide")) {
        //     if (res.length == 0) {
        //       document
        //         .querySelector(".teldTreeListContent_outSide")
        //         .querySelector(".noData").style.display = "block";
        //       document
        //         .querySelector(".teldTreeListContent_outSide")
        //         .querySelector(".Teld_Table_Content").style.display = "none";
        //     } else {
        //       document
        //         .querySelector(".teldTreeListContent_outSide")
        //         .querySelector(".noData").style.display = "none";
        //       document
        //         .querySelector(".teldTreeListContent_outSide")
        //         .querySelector(".Teld_Table_Content").style.display = "block";
        //     }
        //   }

        //   this.BindResize();
        //   return;
        // }
        window.delaySearch_treeHelper = window.setTimeout(async () => {
          if (!this.teldTree_search_inner.value) {
            treeListContent
              .querySelector(".teldTree_search_inner")
              .querySelector(".tree_helper_history_icon")
              .click();
            return;
          }
          this.treeListContent.querySelector("#Table_Tr_Content").innerHTML =
          "";
        let res = this.options.search({
          filter: this.teldTree_search_inner.value,
        });
        if (res instanceof Promise) {
          res = await res;
        }
        if (!res) {
          res = [];
        }
        this.RenderSelect([]);

        this.treeListContent.querySelector("#Tree_Tr_Content").style.display =
          "none";
        this.treeListContent.querySelector(
          ".Teld_Table_Hepler_Table"
        ).style.display = "";
        this.tableData = res;
        // this.RenderTable()
        res.forEach((item, index) => {
          item.f_id = index + 1 + "";
          this.treeListContent
            .querySelector("#Table_Tr_Content")
            .appendChild(this.CreateTable(item));
        });
        if (document.querySelector(".teldTreeListContent_outSide")) {
          if (res.length == 0) {
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".noData").style.display = "flex";
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".Teld_Table_Content").style.display = "none";
          } else {
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".noData").style.display = "none";
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".Teld_Table_Content").style.display = "block";
          }
        }

        this.BindResize();
        }, 500);
      };
      // this.teldTree_search_inner.onblur = () => {
      //   setTimeout(() => {
      //     this.RenderSelect([]);
      //   }, 200);
      // };
    }, 0);
    //treeListContent.style.top = (parentNodePosition.top+34 )+'px'
    this.elemnt_input_outside.setAttribute("disabled", true);
    document.addEventListener("click", (e) => {
      if (!document.querySelector(".tree_" + this.comID)) return;
      if (
        this.element.contains(e.target) ||
        document.querySelector(".tree_" + this.comID).contains(e.target)
      ) {
        return;
      }
      for (let i in window.TeldTreeListHelperInstance) {
        window.TeldTreeListHelperInstance[i].CloseDrop();
      }
    });
    //监听事件
    let closeEle = this.dropEle.querySelector(
      ".Teld_Tree_Hepler_Table_footer_close"
    );
    closeEle.addEventListener("click", this.options.close);
    //保存事件
    let saveEle = this.dropEle.querySelector(
      ".Teld_Tree_Hepler_Table_footer_save"
    );
    saveEle.addEventListener("click", this.Response.bind(this));
  };
  TeldTreeListHelper.prototype.renderPosition = function(notBindResize) {
    let position = this.InputElementOutSidePosition(
      notBindResize
        ? getElementPosition(this.treeListContent).top<getElementPosition(this.refField).top
          ? "bottom"
          : "top"
        : ""
    );
    delete position.left;
    if(getElementPosition(this.treeListContent).top<getElementPosition(this.refField).top){
      delete position.top
      position.bottom=0
    }else{
      delete position.bottom
      position.top=0
    }


    for (let i in position) {
      if (i == "top") {
        this.treeListContent.style.removeProperty("bottom");
      } else if (i == "bottom") {
        this.treeListContent.style.removeProperty("top");
      }
      this.treeListContent.style[i] = position[i];
    }
    //最大宽度限制
    if (this.treeListContent.offsetWidth > this.maxWidth) {
      this.treeListContent.width = this.maxWidth + "px";
    }
    //左右位置处理
    /**
     * @ 如果显示宽度小于当前窗口宽度，宽度设置为当前窗口宽度，
     * 右侧超出，向左侧平易
     *
     */
    let left = this.treeListContent.style.left.replace(/px/gi, "");
    let diffWidth =
      document.documentElement.clientWidth -
      left -
      this.treeListContent.clientWidth;
    if (
      this.treeListContent.clientWidth > document.documentElement.clientWidth ||
      this.options.isMobile
    ) {
      this.treeListContent.style.width =
        document.documentElement.clientWidth + "px";
      this.treeListContent.style.left = "0";
    } else if (diffWidth < 0) {
      this.treeListContent.style.left = left - diffWidth * -1 + "px";
    }
    if (document.querySelector(".Teld_Table_Content") && this.treeListContent) {
      let parentNode = getElementPosition(this.element);
      let height_history = this.treeListContent.querySelector(
        ".teldTree_history"
      ).offsetHeight;
      let height
      const parentRect = this.refField.getBoundingClientRect();
      if (this.treeListContent.style.bottom) {

        const availableHeight = parentRect.top - 20 - height_history -parentRect.height/2; // 20 为顶部边距

        // 设置父容器的 bottom 值，并移除 top 属性
        let refTPopupProxy = this.treeListContent.parentNode.parentNode;
        refTPopupProxy.style.bottom = `${ window.innerHeight - parentRect.top - 24}px`;
        refTPopupProxy.style.removeProperty("top");
        height=availableHeight
      } else {
        height = window.innerHeight - parentRect.top - parentRect.height - 80  - height_history;
      }
      debugger
      if (
        document
          .querySelector(".Teld_Table_Content").style.maxHeight.replace(/px/gi, "") > height &&
        this.treeListContent.style.opacity != 1
      ) {
        document.querySelector(".Teld_Table_Content").style.maxHeight =
          (height < 200 ? 200 : height) + "px";
      }
      this.treeListContent.style.height = "100%";
      this.treeListContent.style.opacity = "1";
      this.treeListContent.style.flex = "1 1 auto";
      this.treeListContent.style.display = "flex";
      this.treeListContent.style.flexDirection = "column";
    } else {
      setTimeout(() => {
        if (document.querySelector(".Teld_Table_Content")) {
          let height_history = this.treeListContent.querySelector(
            ".teldTree_history"
          ).offsetHeight;
          let parentNode = getElementPosition(this.element);
          let height
          if (this.treeListContent.style.bottom) {
            height = parentNode.top + parentNode.height - 190 - height_history;
          } else {
            height = window.innerHeight - parentNode.top - 190 - height_history;
          }
          if (
            document
              .querySelector(".Teld_Table_Content")
              .style.maxHeight.replace(/px/gi, "") > height &&
            this.treeListContent.style.opacity != 1
          ) {
            document.querySelector(".Teld_Table_Content").style.maxHeight =
              height < 0 ? 0 : height + "px";
          }
        }

        this.treeListContent.style.height = "100%";
        this.treeListContent.style.opacity = "1";
        this.treeListContent.style.flex = "1 1 auto";
        this.treeListContent.style.display = "flex";
        this.treeListContent.style.flexDirection = "column";
      }, 300);
    }
    this.teldTree_search_inner = this.options.teldTree_search_inner
    //this.treeListContent.querySelector(".teldTree_search_inner").querySelector("input");

    this.BindResize();
  };
  TeldTreeListHelper.prototype.LazySearch = function() {

    if (window.delaySearch_treeHelper) {
      window.clearTimeout(window.delaySearch_treeHelper);
      window.delaySearch_treeHelper = null;
    }
    window.delaySearch_treeHelper = window.setTimeout(async () => {
     if(  window.CreateSearchTable){
      window.CreateSearchTable.forEach(item=>{
        window.clearTimeout( item)
      })
      window.CreateSearchTable=null
     }
      this.isSearching = true;
      this.treeListContent
        .querySelector(".teldTree_search_inner")
        .querySelector(".tree_helper_history_icon").style.display = "block";
      this.handleData = JSON.parse(this.oldHandleData);

      let handleData = this.handleData.filter((item) => {
        let has = false;
        for (let i in item) {
          //console.log(item[i],typeof item[i] == 'string',item[i].toString().indexOf(this.teldTree_search_inner.value)!=-1)
          if (
            item[i] == this.teldTree_search_inner.value ||
            (typeof item[i] == "string" &&
              item[i].indexOf(this.teldTree_search_inner.value) != -1)
          ) {
            has = true;
          }
        }
        return has;
      });
      const myTbody = document.querySelector("#Tree_Tr_Content");
      if(!myTbody) return //this.LazySearch()
      myTbody.innerHTML = "";
      let pList = [];
      if(this.teldTree_search_inner.value){
        handleData.forEach((item) => {
          let pNodeList = this.GetPList(item);
          pNodeList = pNodeList.filter(
            (jj) =>
              !pList.some((kk) => kk[this.valueField] == jj[this.valueField])
          );
          pList = pList.concat(pNodeList);
          let ChNodeList = this.GetChNodeList(item);
          ChNodeList = ChNodeList.filter(
            (jj) =>
              !pList.some((kk) => kk[this.valueField] == jj[this.valueField])
          );
          pList = pList.concat(ChNodeList);
        });
      }

      let root = [];
      pList = pList.filter(
        (jj) =>
          !handleData.some((kk) => kk[this.valueField] == jj[this.valueField])
      );
      let treeList = handleData.concat(pList);
      const idMapping = treeList.reduce((acc, el, i) => {
        acc[el[this.options.lable_pid]] = i;
        return acc;
      }, {});
      // const idMapping = treeList.reduce((acc, el, i) => {
      //   acc[
      //     el[
      //       this.options.type == 1
      //         ? this.options.value_pid
      //         : this.options.lable_pid
      //     ]
      //   ] = i;
      //   return acc;
      // }, {});
      this.fIdChildMapList = idMapping;
      setTimeout(() => {
        if (document.querySelector(".teldTreeListContent_outSide")) {
          if (treeList.length == 0) {
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".noData").style.display = "flex";
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".Teld_Table_Content").style.display = "none";
          } else {
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".noData").style.display = "none";
            document
              .querySelector(".teldTreeListContent_outSide")
              .querySelector(".Teld_Table_Content").style.display = "block";
          }
        }
      }, 100);
      treeList.forEach((el) => {
        // 判断根节点
        //todo 分级码 与 pid 需要独立处理
        //el.Code == '01'
        let label = this.options.value_pid;
        //pid类型

        // 用映射表找到父元素

        let parentEl = null;
        if (this.options.type == 1) {
          let step = "";
          //固定步长
          let firstStep = "";
          if (this.options.isClassiFicationSteps) {
            step = this.options.classiFicationStep;
            firstStep = step;
          } else {
            //非固定步长 动态计算
            let classiFicationStepRule = this.options.classiFicationStepRule.split(
              "-"
            );
            firstStep = classiFicationStepRule[0];
            let currectIndex = 0;
            classiFicationStepRule.reduce((prev, cur, index, arr) => {
              if (prev == el[label].length) {
                currectIndex = index;
              }
              return prev * 1 + cur * 1;
            });
            step = classiFicationStepRule[currectIndex];
          }
          if (el[label].length == firstStep) {
            root.push(el);
            return;
          }
          //层级码模式
          parentEl =
            treeList[
              idMapping[
                el[label]
                  .toString()
                  .substr(0, el[label].toString().length - step)
              ]
            ];
        } else {
          //层级码类型 看顶级分级吗的长度
          if (el[label] == this.options.parentId) {
            root.push(el);
            return;
          }
          //pid；类型
          parentEl = treeList[idMapping[el[label]]];
        }
        if (parentEl) {
          // 把当前元素添加到父元素的`children`数组中
          parentEl[this.childNodeName] = [
            ...(parentEl&& parentEl[this.childNodeName] ? parentEl[this.childNodeName] : []),
            el,
          ];
          parentEl[this.childNodeName] = parentEl[this.childNodeName].filter(
            (item) => item
          );
        }
        console.log(parentEl);
      });
      this.handleData = this.FlatAndaddSpace(root, 10, "", "-1");
      // this.handleData.forEach(item => {
      // 	if (this.fIdChildMapList['-1'].includes(item.f_id)) {
      // 		myTbody.appendChild(this.CreateTr(item))
      // 	}
      // })
      window.CreateSearchTable=[]
      if(!this.teldTree_search_inner.value){
        this.isSearching=false
      }
      this.handleData.forEach((item,index) => {
        window.CreateSearchTable.push(window.setTimeout(()=>{
          // eval("console.log('执行加载',item)")
          myTbody.appendChild(
            this.CreateTr(item, this.teldTree_search_inner.value)
          );
        },1*index))

      });

      for (let i in this.trStatus) {
        this.trStatus[i] = false;
      }
    }, 500);
  };
  TeldTreeListHelper.prototype.BindResize = function() {
      if (this.isBinded) return;
      this.isBinded = true;
      // $(".Teld_Tree_Hepler_Table").colResizable({
      //   liveDrag: true,
      //   draggingClass: "dragging",
      //   resizeMode: "fit", //'overflow'
      // });

      // $(".Teld_Table_Content").on("scroll", function() {
      //   var scrollTop = $(this).scrollTop();
      //   $(".Teld_Tree_Hepler_Table")
      //     .find("thead tr th")
      //     .css({
      //       "-webkit-transform": "-webkit-translateY(" + scrollTop + "px)",
      //       "-mox-transform": "-moz-translateY(" + scrollTop + "px)",
      //       "-ms-transform": "-o-translateY(" + scrollTop + "px)",
      //       "-o-transform": "-ms-translateY(" + scrollTop + "px)",
      //       transform: "translateY(" + scrollTop + "px)",
      //     });
      // });
  };
  TeldTreeListHelper.prototype.GetPName = function(target, str) {
    if (target.proxyName) return target.proxyName;

    if (!str) {
      str = target[this.labelField];
    } else {
      str = target[this.labelField] + "/" + str;
    }
    let PNode = null;
    if (this.options.type == 1 && this.handleData) {
      //层级码模式
      PNode = this.handleData.filter(
        (filter) =>
          target[this.value_pid] &&
          filter[this.lable_pid] ==
            target[this.value_pid].substr(
              0,
              target[this.value_pid].toString().length - 2
            )
      );
    } else if (this.handleData) {
      //pid；类型
      PNode = this.handleData.filter(
        (filter) => filter[this.lable_pid] == target[this.value_pid]
      );
    }

    if (PNode && PNode[0]) {
      str = this.GetPName(PNode[0], str);
    }

    return str;
  };
  TeldTreeListHelper.prototype.GetPList = function(target, pList) {
    target = this.handleData.find(item=>item[this.options.valueField]==target[this.options.valueField]||item[this.options.valueField]==target.value)
    if(!target) return []
    if (!pList) {
      pList = [];
    }
    let PNode = [];
    PNode = this.handleData.filter(
      (filter) => target.f_id.indexOf(filter.f_id + this.options.linker) == 0
    );
    // if(this.options.type==1){
    // 	//层级码模式
    // 	PNode = this.handleData.filter(filter => target.f_id.indexOf(filter.fi_id+this.options.linker) ==0)

    // }else{
    // 	//pid；类型
    // 	PNode = this.handleData.filter(filter => filter[this.lable_pid] == target[this.value_pid])
    // }
    // pList.push(PNode[0])
    // if (PNode && PNode[0]) {
    // 	this.GetPList(PNode[0], pList)
    // }
    // pList = pList.filter(item=>item)

    return PNode ? PNode : [];
  };
  TeldTreeListHelper.prototype.GetChNodeList = function(target, pList) {
    if (!pList) {
      pList = [];
    }
    let PNode = null;
    PNode = this.handleData.filter(
      (filter) => filter.f_id.indexOf(target.f_id + this.options.linker) == 0
    );

    return PNode ? PNode : [];
  };
  //生成下拉
  TeldTreeListHelper.prototype.RenderSelect = function(select) {
    if (!select) return;

    let html = ``;
    if (select.length > 0) {
      select.forEach((item) => {
        if (this.isLazy) {
          html += `
					<p>
					<span id=${item[this.lable_pid]}>${item.Name}${
            item[this.lable_pid] ? "(" + item[this.lable_pid] + ")" : ""
          }</span>
					</p>
					`;
        } else {
          //获取名称集合
          let name = this.GetPName(item);
          html += `
					<p>
					<span id=${item[this.lable_pid]}>${name}</span>
					</p>
					`;
        }
      });
    }
    if (!html) {
      this.treeListContent
        .querySelector(".teldTree_search_inner")
        .querySelector("#search_select_tree").style.display = "none";
    } else {
      this.treeListContent
        .querySelector(".teldTree_search_inner")
        .querySelector("#search_select_tree").style.display = "block";
    }
    this.treeListContent
      .querySelector(".teldTree_search_inner")
      .querySelector("#search_select_tree").innerHTML = html;
    this.treeListContent
      .querySelector(".teldTree_search_inner")
      .querySelector("#search_select_tree").onclick = (e) => {
      this.handleData = JSON.parse(this.oldHandleData);
      e.stopPropagation();
      e.preventDefault();
      let id =
        e.target.getAttribute("id") ||
        e.target.querySelector("span").getAttribute("id");
      let target = select.find((items) => items[this.lable_pid] == id);
      debugger;
      if (target) {
        if (this.multiple) {
          if (
            !this.checkList.some(
              (kk) => kk[this.valueField] == target[this.valueField]
            )
          ) {
            this.checkList.push(target);
          }
        } else {
          this.checkList = [target];
        }
        this.Response();
      }
    };
  };
  //规整返回值结构返回
  TeldTreeListHelper.prototype.Response = function() {
    this.checkList.forEach((item) => {
      if (this.responseRelationNode == 2 && !this.multiple) {
        let relationIcon = "";
        if (this.relationIcon) {
          relationIcon = this.relationIcon;
        }
        item.proxyName = this.GetPName(item).replace(/\//gi, this.relationIcon);
        if (!item.relationNode) {
          try {
            let handleData = JSON.parse(JSON.stringify(this.handleData));
            let arr1 = item.f_id.split(this.linker);
            item.relationNode = handleData.filter((jj) => {
              let arr2 = jj.f_id.split(this.linker);
              return (
                jj.f_id == item.f_id.split(this.linker)[0] ||
                (item.f_id.indexOf(jj.f_id) == 0 &&
                  arr1[arr2.length - 1] == arr2[arr2.length - 1])
              );
            });
            item.relationNode = JSON.stringify(item.relationNode);
          } catch (e) {
            item.relationNode = `[]`;
            //TODO handle the exception
          }
        }
      } else {
        delete item.proxyName;
      }
    });
    let response={
      data:this.multiple?this.checkList:this.checkList[0]
    }

    this.options.checkData?this.options.checkData(response):''
    setTimeout(()=>{
      if(response.cancel) return
      if (this.multiple) {
        response = JSON.parse(JSON.stringify(this.checkList));
      } else {
        response = JSON.parse(
          JSON.stringify(this.checkList[0] ? this.checkList[0] : [])
        );
      }
        this.confirm(response);
        this.CloseDrop();
        //写入缓存
        if (this.historyEnable) {
          this.localstrogeSetItem(response);
        }
        if (this.checkList.length > 0) {
          this.ShowTag();
          this.elemnt_input_outside.setAttribute('placeholder','')
          // this.elemnt_input_outside.style.display = "none";
        } else {
          this.elemnt_input_outside.setAttribute('placeholder',this.options.placeholder)
          this.elemnt_input_outside.style.display = "block";
        }
    },50)


    // return this.checkList;
  };
  TeldTreeListHelper.prototype.localstrogeSetItem = function(data) {
    debugger;
    if (!data) return;

    let historyData = this.GetHistory();
    //数组
    if (data instanceof Array) {
      historyData = historyData.filter(
        (item) =>
          !(
            item instanceof Array &&
            item.length == data.length &&
            item.every((ll) =>
              data.some((mm) => mm[this.valueField] == ll[this.valueField])
            )
          )
      );
      //if(!historyData[0])return
      historyData.unshift(data);
    } else {
      if (!data[this.valueField]) return;
      //对象
      historyData = historyData.filter(
        (item) => data[this.valueField] != item[this.valueField]
      );
      historyData.unshift(data);
    }
    if (!historyData) {
      historyData = [];
      return;
    }
    historyData = historyData.filter(
      (item) => item instanceof Array || item[this.valueField]
    );
    if (this.historySaveCount) {
      historyData = historyData.slice(0, this.historySaveCount);
    }
    localStorage["tree_helper_" + this.helperCode] = JSON.stringify(
      historyData
    );
    this.RenderHIstory();
  };
  TeldTreeListHelper.prototype.GetHistory = function() {
    let localstroge_history = localStorage["tree_helper_" + this.helperCode];
    if (localstroge_history) {
      return JSON.parse(localstroge_history);
    }
    return [];
  };
  //生成历史记录
  TeldTreeListHelper.prototype.RenderHIstory = function() {
    if (!this.historyEnable) return;
    if (!this.dropEle) return;
    debugger;
    let pNode = this.dropEle.querySelector(".teldTree_history");
    let historyData = this.GetHistory();
    let html = ``;
    historyData.forEach((item, index) => {
      let name = ``;
      let val = ``;
      if (item instanceof Array) {
        item.forEach((kk) => {
          name += kk[this.labelField] + "、";
          val += kk[this.valueField] + ",";
        });
        if (val) {
          val = val.substr(0, val.length - 1);
          name = name.substr(0, name.length - 1);
        }
      } else {
        name = item.proxyName || item[this.labelField];
        val = item[this.valueField];
      }
      if (name) {
        html += `
			<span data-index=${index}>
				<i id=${val} title='${name}' class='tree_helper_history_tags' data-index=${index}>
					${name}
				</i>
				<span class='tree_helper_history_icon' data-index=${index}>
				<i class='close_tags ' data-index=${index}></i>
				</span>

			</span>
			`;
      }
    });
    pNode.innerHTML = html;
    pNode.onclick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      if (
        e.target.className.indexOf("close_tags") != -1 ||
        e.target.className.indexOf("tree_helper_history_icon") != -1
      ) {
        let index = e.target.getAttribute("data-index");
        if (!index) return;
        let historyData = this.GetHistory();
        historyData.splice(index, 1);
        localStorage["tree_helper_" + this.helperCode] = JSON.stringify(
          historyData
        );
        this.RenderHIstory();
      } else {
        let index = e.target.getAttribute("data-index");
        if (!index) return;
        let historyData = this.GetHistory();
        if (this.multiple) {
          historyData[index].forEach((jj) => {
            if (!this.checkList.some((kk) => kk.f_id == jj.f_id)) {
              this.checkList.push(jj);
            }
          });
        } else {
          if (
            !this.checkList.some(
              (kk) => kk[this.valueField] == historyData[index][this.valueField]
            )
          ) {
            this.checkList = [historyData[index]];
          } else {
            return this.CloseDrop();
          }
        }
        this.Response();
      }
    };
  };
  //生成下拉框位置信息
  TeldTreeListHelper.prototype.InputElementOutSidePosition = function(type) {
    let position = {};
    let parentNode = getElementPosition(this.element);
    //获取当前下拉的高度
    let contentHeight = this.treeListContent.offsetHeight;

    position.left = parentNode.left + "px";

    if (type) {
      if (type == "top") {
        position.top = parentNode.top + parentNode.height + "px";
      } else {
        position.bottom = window.innerHeight - parentNode.top + "px";
      }
    } else if (
      window.innerHeight -
        (parentNode.top + parentNode.height) -
        contentHeight >=
        0 ||
      parentNode.top < window.innerHeight - parentNode.top
    ) {
      position.top = parentNode.top + parentNode.height + "px";
    } else {
      position.bottom = window.innerHeight - parentNode.top + "px";
    }

    if (this.dropDownWidth == "auto") {
      position.width = this.getDropDownWidth()//parentNode.width + "px";
    } else if (this.dropDownWidth.indexOf("%")!=-1) {
      position.width =
        (this.dropDownWidth.replace(/%/, "") / 100) * parentNode.width + "px";
    } else {
      position.width =this.dropDownWidth||this.getDropDownWidth() ;
    }

    //init
    return position;
  };
  //初始化tree
  TeldTreeListHelper.prototype.InitTree = async function() {
    if(  window.CreateSearchTable){
      window.CreateSearchTable.forEach(item=>{
        window.clearTimeout(item)
      })
      window.CreateSearchTable=null
     }
    const myTbody = document.querySelector("#Tree_Tr_Content");
    //this.treeListContent.style.opacity = '0'
    //只有初次加载全量加载节点，否则走缓存
    let params = null;

    if (!this.handleData || this.isSearching) {
      if (this.isSearching) {
        this.isSearching = false;
        myTbody.innerHTML = "";
        this.handleData = JSON.parse(this.oldHandleData);
      }
      if (this.isLazy) {
        params = this.options.parentId; //0//修改为自己配置
      }
      let treeList = this.handleData ? this.handleData : this.loadNode(params);
      if (treeList instanceof Promise) {
        treeList = await treeList;
      }
      treeList = _.cloneDeep(treeList)
      // setTimeout(()=>{
      // 	if(treeList.length==0){
      // 		document.querySelector('.teldTreeListContent_outSide').querySelector('.noData').style.display='block'
      // 	}else{
      // 		document.querySelector('.teldTreeListContent_outSide').querySelector('.noData').style.display='none'
      // 	}
      // },100)

      if (!this.isLazy) {
		/**
		 * 大致思路，通过创建索引关系表，降低查询难度
		 * 依赖对象浅拷贝指向同一内存地址的特性构造树结构
		 */
		// 创建父子映射关系
        const idMapping = treeList.reduce((acc, el, i) => {
          acc[el[this.options.lable_pid]] = i;
          return acc;
        }, {});
        let root = [];
        treeList.forEach((el) => {
          // 判断根节点
          //todo 分级码 与 pid 需要独立处理
          //el.Code == '01'
          let label = this.options.value_pid;
          //pid类型
          // 用映射表找到父元素
          let parentEl = null;
          if (this.options.type == 1) {
            //层级码类型 看顶级分级吗的长度
			let step_start = this.options.isClassiFicationSteps?this.options.classiFicationStep:this.options.classiFicationStepRule.split("-")[0]
            if (el[label].length ==step_start) {
              root.push(el);
              return;
            }
            let step = 0;
            //固定步长
            if (this.options.isClassiFicationSteps) {
              step = this.options.classiFicationStep;
            } else {
              //非固定步长 动态计算
              let classiFicationStepRule = this.options.classiFicationStepRule.split(
                "-"
              );
              let currectIndex = 0;
              classiFicationStepRule.reduce((prev, cur, index, arr) => {
                if (prev == el[label].length) {
                  currectIndex = index;
                }
                return prev * 1 + cur * 1;
              });
              step = classiFicationStepRule[currectIndex];
            }
            //层级码模式
            parentEl =
              treeList[
                idMapping[
                  el[label]
                    .toString()
                    .substr(0, el[label].toString().length - step)
                ]
              ];
          } else {
            //pid类型看顶级pid
            if (el[label] == this.options.parentId) {
              root.push(el);
              return;
            }
            //pid；类型
            parentEl = treeList[idMapping[el[label]]];
          }
          if (parentEl) {
            // 把当前元素添加到父元素的`children`数组中
            parentEl[this.childNodeName] = [
              ...(parentEl&&parentEl[this.childNodeName] ? parentEl[this.childNodeName] : []),
              el,
            ];
            parentEl[this.childNodeName] = parentEl[this.childNodeName].filter(
              (item) => item
            );
          }
        });
        treeList = root;
      }
      this.handleData = this.FlatAndaddSpace(treeList.slice(0), 10, "", "-1");
      // eval('console.log("获取到树节点规整后信息：",this.handleData)')
      this.oldHandleData = JSON.stringify(
        this.handleData ? this.handleData : []
      );
      // setTimeout(() => {
      //   document.querySelector(".Teld_Table_Content").style.height =
      //     document.querySelector(".Teld_Table_Content").offsetHeight + "px";
      // }, 100);
    }
    setTimeout(() => {
      if (document.querySelector(".teldTreeListContent_outSide")) {
        if (this.handleData.length == 0) {
          document
            .querySelector(".teldTreeListContent_outSide")
            .querySelector(".noData").style.display = "flex";
          document
            .querySelector(".teldTreeListContent_outSide")
            .querySelector(".Teld_Table_Content").style.display = "none";
        } else {
          document
            .querySelector(".teldTreeListContent_outSide")
            .querySelector(".noData").style.display = "none";
          document
            .querySelector(".teldTreeListContent_outSide")
            .querySelector(".Teld_Table_Content").style.display = "block";
        }
      }
    }, 100);
    this.handleData.forEach((item) => {
      if (this.fIdChildMapList["-1"].includes(item.f_id)&&myTbody) {
        myTbody.appendChild(this.CreateTr(item));
      }
    });
  };
  //规整数据
  TeldTreeListHelper.prototype.FlatAndaddSpace = function(
    tree,
    pre = 0,
    idPre = "",
    pid = "",
    plevel = 0
  ) {
    if (!tree) return;

    let data = [];
    const len = tree.length;
    for (let i = 0; i < len; i++) {
      if (this.fIdChildMapList[pid]) {
        if(!this.fIdChildMapList[pid].push){
          this.fIdChildMapList[pid]=[  this.fIdChildMapList[pid]]
        }
        this.fIdChildMapList[pid].push(`${idPre}${i + 1}`);
      } else {
        this.fIdChildMapList[pid] = [`${idPre}${i + 1}`];
      }
      if (!tree[i]) return;
      if (!tree[i].id) {
        tree[i].id = uuid();
      }
      tree[i].preSpace = pre;
      tree[i].f_id = `${idPre}${i + 1}`;
      tree[i].level = plevel + 1;
      this.trStatus[idPre + i] = true;
      const obj = {};
      Object.keys(tree[i]).forEach((key) => {
        if (key != this.childNodeName) {
          //null 转换存在问题
          //obj[key] = tree[i][key] === null ? '-' : tree[i][key]
          obj[key] = tree[i][key];
        }
      });
      data.push(obj);
      if (tree[i][this.childNodeName]) {
        let preTarget = 0;
        for (let i = 0; i < this.indent; i++) {
          preTarget++;
        }
        let currentPre = pre + preTarget;
        data = data.concat(
          this.FlatAndaddSpace(
            tree[i][this.childNodeName],
            currentPre,
            `${tree[i].f_id}${this.linker}`,
            tree[i].f_id,
            tree[i].level
          )
        );
      }
    }
    return data;
  };
  //创建表格
  TeldTreeListHelper.prototype.CreateTr = function(data, searchData) {
    if (!data) {
      return;
    }
    const tr = document.createElement("tr");
    let level = data.level % 2 !== 0 ? "odd" : "even";

    let icon = this.fIdChildMapList[data.f_id]
      ? '<i class="icon ' +
        (this.isSearching ? this.foldIcon : this.openIcon) +
        '" style="margin-left:' +
        data.preSpace +
        'px;font-size:12px;margin-right: 8px;"></i>'
      : '<i class="icon none" style="margin-left:' +
        data.preSpace +
        'px;margin-right: 4px;"></i>';
    let disabled = this.fIdChildMapList[data.f_id];
    if (this.isLazy && data[this.leaf] != this.leafValue) {
      icon =
        '<i class="icon ' +
        (this.isSearching ? this.foldIcon : this.openIcon) +
        '" style="margin-left:' +
        data.preSpace +
        'px;font-size:12px;margin-right: 8px;"></i>';
      disabled = true;
    } else if (this.isLazy && data[this.leaf] == this.leafValue) {
      icon =
        '<i class="icon none" style="margin-left:' +
        data.preSpace +
        'px;margin-right: 4px;"></i>';
      disabled = false;
    }
    // 如果非今选择最后一个阶段 取消限制
    if (!this.onlyCheckedNotLeaf) {
      disabled = false;
    }
    tr.className = `f_id_${data.f_id
      .split(this.linker)
      .join("_")} level_${level} tree_table_tr ${
      this.fIdChildMapList[data.f_id] ? "c_pointer" : "c_pointer"
    }`;
    tr.setAttribute("f_id", data.f_id);
    tr.setAttribute("id", data[this.lable_pid]);
    let str = `
		`;
    let checkBoxContent = "";
    this.fieldMapping.forEach((item, index) => {
      if (!item) return;
      let style = ``;
      if (item.textAlign) {
        style += `text-align:${item.textAlign};`;
      }
      if (item.width) {
        item.width = item.width.replace(/px/gi, "" + "px");
        style += `width:${item.width};min-width:${item.width}`;
      }
      let checked = this.checkList.some(
        (ii) => ii[this.valueField] == data[this.valueField]
      );

      if (checked) {
        tr.setAttribute("class", tr.className + " level_checked");
      }
      let checkBox = ``;
      if (this.multiple && !index) {
        checkBox = `
				<input
				  class="custom-checkbox"
				  id='check_${data.f_id} '
				  ${disabled ? 'disabled="disabled"' : ""}
				  ${checked ? 'checked="checked"' : ""}
				  type="checkbox" />
				<label >
				</label>
				`;
      }
      let dataStr = data[item.field];
      let placeholder = dataStr;
      if (searchData && dataStr) {
        var reg = new RegExp(searchData, "ig");
        dataStr = dataStr.replace(
          reg,
          `<i style="font-style:normal;background:var(--t-color-background)">${searchData}</i>`
        );
      }
      str += `<td style=${style} title='${placeholder}'>
			${checkBox ? checkBox : ""}
					<span class="icon_content">

					${
            item.field == "checkBoxTag"
              ? checkBox
              : item.field == this.showIconField
              ? icon
              : '<i class="icon none" style="margin-left:10px"></i>'
          }
					</span>
					${item.field == "checkBoxTag" ? "" : dataStr}
				</td>`;
      checkBoxContent = "";
    });

    //myTbody.innerHTML = innerHTML
    tr.innerHTML = str;
    let self = this;
    let clickNum = 0;


    tr.addEventListener("dblclick", function(e) {
      if (!self.multiple) {
        self.HandleClick(e, this, false, true);
      }
    });
    tr.addEventListener("click", function(e) {
      self.HandleClick(e, this);
    });
    return tr;
  };
  TeldTreeListHelper.prototype.CreateTable = function(data) {
    if (!data) {
      return;
    }
    const tr = document.createElement("tr");
    let level = data.level % 2 !== 0 ? "odd" : "even";

    // let icon = this.fIdChildMapList[data.f_id] ? '<i class="icon ' + this.openIcon +
    // 	'" style="margin-left:' +
    // 	data.preSpace + 'px"></i>' :
    // 	'<i class="icon none" style="margin-left:' + data.preSpace + 'px"></i>'
    // if (this.isLazy && !data[this.leaf]) {
    // 	icon = '<i class="icon ' + this.openIcon + '" style="margin-left:' + data.preSpace + 'px"></i>'
    // }
    tr.className = `f_id_${data.f_id
      .split(this.linker)
      .join("_")} level_${level} tree_table_tr ${
      this.fIdChildMapList[data.f_id] ? "c_pointer" : "c_pointer"
    }`;
    tr.setAttribute("f_id", data.f_id);
    tr.setAttribute("id", data[this.lable_pid]);

    let str = `
		`;
    this.fieldMapping.forEach((item) => {
      let style = ``;
      if (item.textAlign) {
        style += `text-align:${item.textAlign};`;
      }
      if (item.width) {
        item.width = item.width.replace(/px/gi, "") + "px";
        style += `width:${item.width};`;
      }
      let checkBox = `
			<input
			  class="custom-checkbox"
			  id="myCheckbox"
			  type="checkbox" />
			<label for="myCheckbox">
			</label>
			`;

      str += `<td style=${style}>
					${item.field == "checkBoxTag" ? checkBox : data[item.field]}
				</td>`;
    });
    let checked = this.checkList.some((ii) => ii.f_id == data.f_id);
    if (checked) {
      tr.setAttribute("class", tr.className + " level_checked");
    }
    tr.innerHTML = str;
    let self = this;
    tr.addEventListener("click", function(e) {
      self.HandleClickTable(e, this);
    });
    delete data.f_id;
    return tr;
  };
  TeldTreeListHelper.prototype.HandleClickTable = async function(e, ele) {
    const id = ele.getAttribute("id");
    let target = this.tableData.find((item) => item[this.lable_pid] == id);
    let isClickIcon = false
    //如果点击下拉按钮
    if (
      e.target.getAttribute("class") &&
      e.target.getAttribute("class").indexOf("icon_content") != -1
    ) {
      if (
        e.target.querySelector("i") &&
        e.target
          .querySelector("i")
          .getAttribute("class")
          .indexOf("none") == -1
      ) {
        isClickIcon = true;
      }
    } else if (
      e.target.getAttribute("class") &&
      e.target.getAttribute("class").indexOf("icon") != -1
    ) {
      isClickIcon = true;
    }
    debugger
    //只能选中非叶子节点
    // if (this.onlyCheckedNotLeaf && fid&&this.fIdChildMapList[fid] && !isClickIcon) {
    // e.stopPropagation()
    // e.preventDefault()
    // return false
    // }
    //选中状态先取消
    if (ele.className.indexOf("level_checked") != -1) {
      let className = ele.className.replace(/level_checked/gi, "");
      ele.setAttribute("class", className);
      this.checkList = this.checkList.filter(
        (item) => item[this.lable_pid] != id
      );
      if (ele.querySelector(".custom-checkbox")) {
        ele.querySelector(".custom-checkbox").removeAttribute("checked");
      }
      return;
    }

    //先清空选中
    if (!this.multiple) {
      let level_checked = document.querySelectorAll(".level_checked");
      level_checked.forEach((item) => {
        item.setAttribute(
          "class",
          item.getAttribute("class").replace(/ level_checked/gi, "")
        );
      });
    }

    ele.setAttribute("class", ele.getAttribute("class") + " level_checked");
    if (ele.querySelector(".custom-checkbox")) {
      ele.querySelector(".custom-checkbox").setAttribute("checked", "checked");
    }

    if (!this.multiple) {
      this.checkList = [];
    }

    this.checkList = this.checkList.filter(
      (item) => item[this.valueField] != target[this.valueField]
    );
    this.checkList.push(target);
  };

  //点击
  TeldTreeListHelper.prototype.HandleClick = async function(
    e,
    ele,
    nottree,
    dblclick
  ) {
    let isClickIcon = false;
    const fid = ele.getAttribute("f_id");
    let tid = ele.getAttribute("id");
    const showChild =
      typeof this.trStatus[fid] == "undefined" ? true : this.trStatus[fid];
    let target = this.handleData.filter((item) => item.f_id == fid)[0];

    //如果点击下拉按钮
    if (
      e.target.getAttribute("class") &&
      e.target.getAttribute("class").indexOf("icon_content") != -1
    ) {
      if (
        e.target.querySelector("i") &&
        e.target
          .querySelector("i")
          .getAttribute("class")
          .indexOf("none") == -1
      ) {
        isClickIcon = true;
      }
    } else if (
      e.target.getAttribute("class") &&
      e.target.getAttribute("class").indexOf("icon") != -1
    ) {
      isClickIcon = true;
    }
    debugger
      //只能选中非叶子节点
      let _className = e.target.querySelector("i")?.className

      if (this.onlyCheckedNotLeaf &&  !isClickIcon&&ele.querySelectorAll('.icon.none').length!=ele.querySelectorAll('.icon').length) {
        e.stopPropagation()
        e.preventDefault()
        return false

      }
  //只能选中非叶子节点
  // if (this.onlyCheckedNotLeaf &&!!this.fIdChildMapList[fid]){
  //   if((((e.target.querySelector("i")&&e.target.querySelector("i").className&&e.target.querySelector("i").className.indexOf('icon')!=-1&& e.target.querySelector("i").className != "icon none")||(!e.target.querySelector("i")&&!isClickIcon)))) ){

  //   }
  //   e.stopPropagation()
  //   e.preventDefault()
  //   return false
  // }
    //选中状态先取消ß
    if (ele.className.indexOf("level_checked") != -1 && !isClickIcon&&!dblclick) {
      let className = ele.className.replace(/level_checked/gi, "");
      ele.setAttribute("class", className);
      this.checkList = this.checkList.filter((item) => item.f_id != fid&&item[this.lable_pid] != tid);
      if (ele.querySelector(".custom-checkbox")) {
        ele.querySelector(".custom-checkbox").removeAttribute("checked");
      }
      //强制关联&&多选 初次选中 打开加载
      if (
        this.options.forcedAssociation &&
        this.options.multiple &&
        this.checkList.every(
          (item) => item[this.valueField] != target[this.valueField]
        )
      ) {
        this.checkList.push(target);
      }
      return;
    }


    //先清空选中
    if (!this.multiple && !isClickIcon) {
      if(this.checkList.some(
        (item) => item[this.valueField] != target[this.valueField]
      )&&dblclick){
        return this.Response();
      }
      let level_checked = document.querySelectorAll(".level_checked");
      level_checked.forEach((item) => {
        item.setAttribute(
          "class",
          item.getAttribute("class").replace(/ level_checked/gi, "")
        );
      });
    }
    if (!isClickIcon) {
      ele.setAttribute("class", ele.getAttribute("class") + " level_checked");
      if (ele.querySelector(".custom-checkbox")) {
        ele
          .querySelector(".custom-checkbox")
          .setAttribute("checked", "checked");
      }
    }
    if (!this.multiple && !isClickIcon) {
      this.checkList = [];
    }
    if (!isClickIcon) {

      this.checkList = this.checkList.filter(
        (item) => item[this.valueField] != target[this.valueField]
      );
      this.checkList.push(target);
      //强制关联&&多选 初次选中 打开加载
      if (
        this.options.forcedAssociation &&
        this.options.multiple &&
        this.checkList.every(
          (item) => item[this.valueField] != target[this.valueField]
        )
      ) {
        this.checkList.push(target);
      }
      if (dblclick) {
        return this.Response();
      }
      return;
    }

    if (nottree) return;
    if (
      !this.fIdChildMapList[fid] &&
      target[this.leaf] != this.leafValue &&
      this.isLazy
    ) {
      debugger;
      let resData = this.loadNode(target[this.lable_pid]);
      if (resData instanceof Promise) {
        let hasIconElement = ele.querySelectorAll(".icon");
        let targetLoadEle = "";
        hasIconElement.forEach((item) => {
          if (item.className.indexOf("none") === -1) {
            targetLoadEle = item;
          }
        });
        let old = targetLoadEle.className;
        targetLoadEle.className = "helpr_tree_loading";
        //替换节点图标为 loading
        resData = await resData;
        if (resData.length == 0) {
          targetLoadEle.className = "icon none";
        } else {
          targetLoadEle.className = old;
        }
      }
      let childrenNode = resData;
      let preTarget = 0;
      for (let i = 0; i < this.indent; i++) {
        preTarget++;
      }
      let currentPre = target.preSpace + preTarget;
      this.handleData = this.handleData.concat(
        this.FlatAndaddSpace(
          childrenNode,
          currentPre,
          target.f_id + this.linker,
          target.f_id,
          target.level
        )
      );
      this.oldHandleData = JSON.stringify(
        this.handleData ? this.handleData : []
      );
    }

    //清空完成
    debugger;
    try {
      this.HandShowAndHide(fid, showChild, ele);
    } catch (error) {}

    this.trStatus[fid] = !showChild;
    let iconClass = showChild
      ? "icon " + this.foldIcon
      : "icon " + this.openIcon;
    let hasIconElement = ele.querySelectorAll(".icon");
    hasIconElement.forEach((item) => {
      if (item.className.indexOf("none") === -1) {
        item.className = iconClass;
        item.className = iconClass;
      }
    });
  };
  //展示

  TeldTreeListHelper.prototype.HandShowAndHide = function(fid, showChild, ele) {
    debugger;
    if (!showChild) {
      // 关闭
      this.GetWillHideFId(fid).forEach((id) => {
        if (document.querySelector(`.f_id_${id.split(this.linker).join("_")}`))
          document.querySelector(
            `.f_id_${id.split(this.linker).join("_")}`
          ).style.display = "none";
        // let className = this.fIdChildMapList[id] ? ("icon "+this.openIcon) : "icon none"
        // document.querySelector(`.f_id_${id.split(this.linker).join('_')}`) ? document
        // 	.querySelector(`.f_id_${id.split(this.linker).join('_')}`)
        // 	.firstElementChild.firstElementChild.className =
        // 	className : ''
        this.trStatus[id] = false;
      });
    } else {
      (this.fIdChildMapList[fid] || []).forEach((id) => {
        if (
          document.querySelector(`.f_id_${id.split(this.linker).join("_")}`) ||
          this.isSearching
        ) {
          document.querySelector(
            `.f_id_${id.split(this.linker).join("_")}`
          ).style.display = "table-row";
          if (
            document
              .querySelector(`.f_id_${id.split(this.linker).join("_")}`)
              .querySelector("." + this.foldIcon.replace(/ /gi, "."))
          ) {
            document
              .querySelector(`.f_id_${id.split(this.linker).join("_")}`)
              .querySelector(
                "." + this.foldIcon.replace(/ /gi, ".")
              ).className = "icon " + this.openIcon;
          }
        } else {
          let target = this.handleData.filter((item) => item.f_id === id)[0];
          //强制关联&&多选 初次选中 打开加载
          if (
            this.options.forcedAssociation &&
            this.options.multiple &&
            this.checkList.every(
              (item) => item[this.valueField] != target[this.valueField]
            ) &&
            ele.className.indexOf("level_checked") != -1
          ) {
            this.checkList.push(target);
          }
          const tr = this.CreateTr(target);
          //Todo 处理加载逻辑
          debugger;
          document
            .querySelector("#Tree_Tr_Content")
            .insertBefore(tr, ele.nextSibling);
          ele = tr;
        }
        this.trStatus[id] = true;
      });
    }
  };
  TeldTreeListHelper.prototype.GetWillHideFId = function(curId) {
    if (!this.fIdChildMapList[curId]) return [];
    var rst = this.fIdChildMapList[curId];
    this.fIdChildMapList[curId].forEach((key) => {
      rst = rst.concat(this.GetWillHideFId(key));
    });
    return rst;
  };
  TeldTreeListHelper.prototype.CloseDrop = function() {

    return
    window.TeldTreeListHelpers = null;
    this.elemnt_input_outside.removeAttribute("disabled");
    let treeListContent = document.querySelector(
      ".teldTreeListContent_outSide"
    );
    if (!treeListContent) {
      return;
    }
    treeListContent.parentNode.removeChild(treeListContent);
  };
  TeldTreeListHelper.prototype.ShowTag = function() {
    if (!this.checkList || !this.checkList.forEach){
      this.elemnt_input_outside.setAttribute('placeholder',this.options.placeholder)
      return (this.element.querySelector(
        ".TeldTreeListHelper_inputelement_input"
      ).style.display = "block");
    }


    let __template__ = ``;
    this.checkList.forEach((item) => {
      if (this.options.readOnly) {
        __template__ += `	<span style="max-width:100%;color:rgba(0,0,0,0.32); background-color:rgba(255,255,255,0.9); border: solid 1px rgba(0,0,0,0.17); overflow: hidden;text-overflow: ellipsis;display: inline-block;white-space: nowrap;">
				${item.proxyName ? item.proxyName : item[this.labelField]}
				</span>`;
      } else {
        __template__ += `	<span style="max-width:100%;">
				<span style="margin: 0;padding: 0;overflow: hidden;text-overflow: ellipsis;display: inline-block;white-space: nowrap;" title="${
          item.proxyName ? item.proxyName : item[this.labelField]
        }">${item.proxyName ? item.proxyName : item[this.labelField]}</span>

				<span class="close_tags_out" style="margin:0;padding:0;background:rgba(0,0,0,0)" data-id=${
          item[this.valueField]
        }>
				<i class='close_tags' style="top:0" data-id=${item[this.valueField]}></i>
				</span>
				</span>`;
      }
    });
    let tagElement = this.element.querySelector(".tags");
    if (this.options.isMobile) {
      tagElement.style.maxWidth = "150px";
    } else {
      tagElement.style.maxWidth = "calc(100% - 40px);";
    }
    tagElement.innerHTML = __template__;
    tagElement.onclick = (e) => {
      let evt = e.target;
      if (
        evt.className.indexOf("close_tags_out") == -1 &&
        evt.className.indexOf("close_tags") == -1
      )
        return;
      let deletData = this.checkList.find(
        (item) => item[this.valueField] == evt.getAttribute("data-id")
      );
      this.checkList = this.checkList.filter(
        (item) => item[this.valueField] != evt.getAttribute("data-id")
      );
      if (this.checkList.length == 0) {
        this.element.querySelector(
          ".TeldTreeListHelper_inputelement_input"
        ).style.display = "block";
      }
      //返回新的列表
      this.Response();
      //返回删除信息
      this.clearn(deletData);
      this.ShowTag();
    };
  };
  TeldTreeListHelper.prototype.setValue = function(obj) {
    if (!obj) {
      this.checkList = [];
      this.element.querySelector(
        ".TeldTreeListHelper_inputelement_input"
      ).style.display = "block";
      this.ShowTag();
      return;
    }
    if (this.options.multiple) {
      if (obj instanceof Array) {
        this.checkList = obj.filter((jj) => jj.value||jj[this.valueField]);
      }
    } else {
      this.checkList = [];
      if (!obj.value || (obj.value && obj.value.pop)) {
        this.element.querySelector(
          ".TeldTreeListHelper_inputelement_input"
        ).style.display = "block";
        this.ShowTag();
        return;
      }

      this.checkList.push(obj);
    }
    this.checkList.forEach((item) => {
      item[this.labelField] = item.label ? item.label : item[this.labelField];
      item[this.valueField] = item.value?item.value:item[this.valueField];
    });
    if (this.checkList.length > 0) {
      this.elemnt_input_outside.setAttribute('placeholder','')
          // this.elemnt_input_outside.style.display = "none";

    }

    this.ShowTag();
  };
  TeldTreeListHelper.prototype.HideTag = function() {
    this.value = this.inputElement.value = this.oldInputElement.value;
    this.element.querySelector(".tsh-tag").style.display = "none";
  };
  TeldTreeListHelper.prototype.setReadOnly = function(flag) {
    this.options.readOnly = flag;
    this.Init(true);
    this.ShowTag();
  };

  TeldTreeListHelper.prototype.BindEvent = function() {
    let pageY = "";

    this.mousewheelfn = (type) => {

      if (this.onmousewheel) return;

      this.onmousewheel = window.setInterval(()=>{
        this.renderPosition(true);
      },1)

      setTimeout(() => {
        window.clearInterval(this.onmousewheel);
        this.onmousewheel = null;
      }, 3000);
      //}
    };
    document.addEventListener("wheel", this.mousewheelfn, {
      passive: false,
      useCapture: false,
    });
    document.addEventListener("mousemove", this.mousewheelfn, {
      passive: false,
      useCapture: false,
    });
  };
  //支持单个或批量初始化
  function Plugin(target, options) {
    var dom = null;
    if (typeof target === "string") {
      dom = document.querySelector(target);
    } else dom = target;
    if (!dom) throw new Error("DOM节点不存在！");
    var comid = dom.getAttribute("data-comId");
    if (window.TeldTreeListHelperInstance.hasOwnProperty(comid)) {
      return window.TeldTreeListHelperInstance[comid];
    }
    //options.comid = comid
    return new TeldTreeListHelper(dom, options);
  }
  window.TeldTreeListHelper = Plugin;
})();
